const {
	Controller
} = require('uni-cloud-router')
module.exports = class OrderController extends Controller {
	constructor(ctx) {
		super(ctx)
	}
	/**
	 * 确定收货
	 */
	async finish() {
		const {
			id
		} = this.ctx.data;
		const {
			uid
		} = this.ctx.auth;
		let order = await this.service.mall.order.getOrderById(id);
		if (!order || order.user_id != uid) {
			return {
				code: -1,
				message: "订单不存在"
			}
		}
		//确定收货，打款到商家账户
		return await this.service.mall.order.finish(order);
	}
	/**
	 * 结算
	 */
	async settlement() {
		let config = this.ctx.getConfigs.config("mall.order");
		let {
			cart_ids,
			goods,
			submit,
			type, //订单来源，购物车/商品
			usedScore, //使用积分数量
			delivery_type, //配送方式
			remarks, //备注
			invoice, //发票
			coupon, //已选择优惠券ID
			address_id
		} = this.ctx.data;
		const {
			uid
		} = this.ctx.auth;
		let userInfo = await this.service.user.user.getCurrentUserInfo(["score", "member"])
		//最大使用积分比例
		let useScoreRate = config.max_use_score_rate;
		//积分兑成现金比例
		let score2moneyRate = config.score_to_money_rate;
		let score = userInfo.score ? userInfo.score : 0;

		let outData = {
			uid,
			freight: 0,
			cart_ids,
			score,
			score2moneyRate,
			check: true
		};
		//获取用户地址信息
		if (address_id) {
			//根据id，查询地址，前端提交过来的其他信息，实际上是不可靠的
			outData.address = await this.service.user.address.getInfoById(uid, address_id)
		} else {
			//获取用户默认地址
			outData.address = await this.service.user.address.getDefaultInfo(uid)
		}
		//获取商品详细信息，查询运费信息
		if (type == "cart") {
			//从购物车查询商品信息
			let cartData = await this.service.mall.cart.getGoodsByIds(cart_ids, uid);
			if (cartData.length == 0) {
				//购物车商品不存在
				outData.check = false;
				return outData;
			}
			goods = cartData;
		}
		let {
			code,
			message,
			discount,
			total,
			group_buying,
			group_buying_id,
			use_score_total: maxDuihuan,
			needScore,
		} = await this.service.mall.goods.getGoodsSkuByCart(goods, userInfo.member, useScoreRate, usedScore,
			score2moneyRate, config.exchange_points_for_cash);
		if (code) {
			return {
				code,
				message
			};
		}
		outData.goodsList = goods;
		outData.discount = discount;
		outData.total = total;
		//计算运费
		if (outData.address) {
			outData.freight = await this.service.mall.express.getExpressByGoods(goods, outData.address)
		}
		//可用积分按商品总金额计算-会员优惠
		outData.canUseScore = maxDuihuan < score ? maxDuihuan : score;
		//必须使用积分数量
		outData.mustUseScore = config.must_use_score;
		//是否使用积分兑换现金
		outData.exchangePointsForCash = config.exchange_points_for_cash;
		//必须使用积分兑换
		if (config.must_use_score) {
			console.log("score < needScore", score, needScore, outData.canUseScore, maxDuihuan, useScoreRate,
				score2moneyRate)
			if (score < needScore) {
				return {
					code: -2,
					message: '积分不足'
				}
			}
			//默认已使用
			usedScore = outData.usedScore = needScore;
		}
		if (submit) {
			if (usedScore > 0) {
				//库存不足情况，不允许提交订单
				if (outData.canUseScore < usedScore) {
					//积分不够扣除
					return {
						code: -2,
						message: "积分不足"
					};
				}
				//增加积分兑换金额，单位是分
				discount += parseFloat(usedScore * score2moneyRate * 100);
				console.log("商城使用积分", usedScore, discount)
			}
			let cart_count = 0;
			let body = goods.map(g => {
				cart_count += parseInt(g.amount);
				return g.name + (g.sku_name ? "+" + g.sku_name : "");
			}).join(",").substr(0, 50);
			//支付倒计时分钟
			let last_pay_time = Date.now() + config.last_pay_minutes * 1000 * 60;
			let total_fee = total - discount + outData.freight;
			let otherData = {};
			if (group_buying) {
				//拼单
				otherData.group_buying = {
					state: 0, //状态0未处理，1已分配数据，拼单中，2拼单成功
					amount: 1,
					goods_id: goods[0].goods_id, //商品ids
					group_buying: goods[0].group_buying, //拼团人数
					group_buying_discount: goods[0].group_buying_discount, //拼团折扣
					group_buying_id,
				}
			}
			//提交商城订单
			let order_id = await this.service.order.mall.save({
				cart_count,
				score2moneyRate,
				freight: outData.freight,
				goods: goods,
				juli: 0,
				address: outData.address,
				platform: this.ctx.context.PLATFORM,
				last_pay_time, //最后支付时间，根据店铺设置
				remarks: remarks,
				state: 0,
				discount,
				goods_total_fee: total, //商品总计
				total_fee, //需要支付的总金额
				invoice,
				coupon,
				body,
				delivery_type,
				score: usedScore,
				user_id: uid,
				...otherData
			});
			//提交公共订单
			/* await this.service.user.order.save(uid, {
				...outData,
				usedScore, //使用积分数量
				remarks, //备注
				invoice, //发票
				coupon, //已选择优惠券ID
				body,
				address_id
			}, "mall", this.ctx.contact); */
			if (type == "cart") {
				//移除购物车
				await this.service.mall.cart.remove(uid, cart_ids)
			}
			//使用积分
			if (usedScore > 0) {
				await this.service.user.user.editScore(uid, usedScore * -1, `商城购物使用积分`);
			}
			return {
				_id: order_id,
				total_fee,
				discount,
				module: "mall",
				body,
			}
		}

		return outData;
	}
	/**
	 * 售后说明
	 */
	async prerefund() {
		return {
			afterServices: this.ctx.getConfigs.config("mall.order.after_services"),
			afterServiceReason: this.ctx.getConfigs.config("mall.order.after_service_reason"),
		}
	}
	/**
	 * 售后，退款、维修
	 */
	async refund() {
		let {
			id,
		} = this.ctx.data;
	}

}
